package com.example.shop_2211.login

import android.content.DialogInterface
import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.SpannableStringBuilder
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.Emp
import com.example.base.entity.LoginEntityResult
import com.example.base.mvvm.BaseActivity
import com.example.shop_2211.MainActivity
import com.example.shop_2211.R
import com.example.shop_2211.WebViewActivity
import com.example.shop_2211.databinding.ActivityLoginCodeBinding
import com.example.shop_2211.room.AppDBUtils
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@Route(path = "/app/LoginCodeActivity")
class LoginCodeActivity : BaseActivity<ActivityLoginCodeBinding,LoginViewModel>() {
    val emps = mutableListOf<Emp>()//定义集合
    override fun initView() {
        for (i in 1..20){//循环添加
            emps.apply {
                add(Emp("张三",i))
            }
        }
        emps.forEach {//打印
            println(it)
        }
        //设置是否可用
        binding.btnLogin.isEnabled = false
        //监听是否可用
        binding.etCode.addTextChangedListener(object:TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                if(s!=null&&s.length==6){
                    binding.btnLogin.isEnabled = true
                }else{
                    binding.btnLogin.isEnabled = false
                }
            }
        })
        //点击获取验证
        binding.btnCode.setOnClickListener {
            if(binding.etPhone.text.toString().isEmpty()){
                ToastUtils.showLong("手机号不能为空")
                return@setOnClickListener
            }
            if(!RegexUtils.isMobileSimple(binding.etPhone.text.toString())){
                ToastUtils.showLong("手机号格式不正确")
                return@setOnClickListener
            }
            viewModel.sendCode(binding.etPhone.text.toString())//发送验证码
            //点击后，文字变成倒计时，且不能点击
            binding.btnCode.isEnabled = false
            lifecycleScope.launch {
                for(i in 15 downTo 1){
                    binding.btnCode.text = "$i 秒后获取"
                    delay(1000)//延迟一秒，形成倒计时的效果
                }
                binding.btnCode.isEnabled = true
                binding.btnCode.text = "获取验证码"
            }
        }
        //点击实现登录
        binding.btnLogin.setOnClickListener {
            if(binding.etPhone.text.toString().isEmpty()){
                ToastUtils.showLong("手机号不能为空")
                return@setOnClickListener
            }
            if(!RegexUtils.isMobileSimple(binding.etPhone.text.toString())){
                ToastUtils.showLong("手机号格式不正确")
                return@setOnClickListener
            }
            if(!binding.cb.isChecked){
                //弹出普通对话框
                AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("阅读了并同意了")
                    .setPositiveButton("确定") { _, _ -> binding.cb.isChecked = true }
                    .setNegativeButton("取消",object:DialogInterface.OnClickListener{
                        override fun onClick(dialog: DialogInterface?, which: Int) {

                        }
                    })
                    .show()

                return@setOnClickListener
            }
            viewModel.loginCode(binding.etPhone.text.toString(),binding.etCode.text.toString())
        }

        //富文本
        val span = SpannableStringBuilder(binding.cb.text.toString())
        span.setSpan(ForegroundColorSpan(Color.RED),6,12,SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE)//文字颜色
        val clickableSpan = object:ClickableSpan(){
            override fun onClick(widget: View) {
                //ToastUtils.showLong("点击了")
             /*   val intent = Intent(this@LoginCodeActivity,WebViewActivity::class.java)
                intent.putExtra("url","http://www.baidu.com")//有下划线证明网址格式正确
                startActivity(intent)*/
                //带参数跳转
                ARouter.getInstance().build("/app/WebViewActivity").withString("url","http://www.baidu.com").navigation()
            }
        }
        span.setSpan(clickableSpan,14,19,SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE)//点击事件
        binding.cb.movementMethod = LinkMovementMethod.getInstance()//一定添加
        binding.cb.text = span


        //跳转到密码登录界面
        binding.btnToLogin.setOnClickListener {
            startActivity(Intent(this,LoginActivity::class.java))
        }

        //点击调用高阶函数
        binding.highFunc.setOnClickListener {
            val i = high { it * it }(10)
            ToastUtils.showLong("调用高级函数的结果是$i")
            val entityList = AppDBUtils.getDb().getUserDao()
                .queryByPhone(SPUtils.getInstance().getString("phone"))
            entityList.forEach {
                Log.d("sss", "initView: 昵称${it.nikeName}令牌${it.token}手机号${it.phone}")
            }

        }
    }

    override fun initData() {
        viewModel.sendCodeSuccess.observe(this){
            if(it.code==200){
                binding.etCode.setText(it.data.content.substring(8,14))
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.sendCodeFail.observe(this){
            ToastUtils.showLong(it)
        }
        viewModel.loginCodeSuccess.observe(this){
            ToastUtils.showLong(it.message)
            if(it.code==200){
                SPUtils.getInstance().put("token",it.data.token)
                SPUtils.getInstance().put("phone",it.data.phone)
                //保存到数据库
                AppDBUtils.getDb().getUserDao().insertUser(it.data)
                //不带参数的路由跳转
                ARouter.getInstance().build("/app/MainActivity").navigation()
                //传值为实体类
                //ARouter.getInstance().build("/app/WebViewActivity").withSerializable("login",it.data).navigation()
            }
        }
        viewModel.loginCodeFail.observe(this){
            ToastUtils.showLong(it)
        }
    }

    override fun getViewModel() = LoginViewModel::class.java

    override fun getLayout(): Int {
        return R.layout.activity_login_code
    }



}
//定义高阶函数
fun high(function:(Int)->Int):(Int)->Int{
    return function
}